package com.itzz.spring_zhoneHeng.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itzz.spring_zhoneHeng.base.JwtTokenUtils;
import com.itzz.spring_zhoneHeng.base.RestResponse;
import com.itzz.spring_zhoneHeng.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

// 登录成功处理
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    MyUserDetailsService myUserDetailsService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //根据前端传输的用户名获取用户信息
        String name = authentication.getName();
        //这里只是获取 UserDetails  并没有做任何的处理
        UserDetails userDetails = myUserDetailsService.loadUserByUsername(name);
        //创建token
        String token = JwtTokenUtils.createToken(userDetails);
        RestResponse ok = RestResponse.ok(token);
        PrintWriter writer = response.getWriter();
        writer.write(new ObjectMapper().writeValueAsString(ok));
        writer.flush();
        writer.close();

    }
}
